import { DownOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, DatePicker, Drawer, Dropdown, Menu, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';

import React, { useRef, useState } from 'react';
import SensorDetail from '../../Locker/List/components/LockerDetail';
import type { TableListItem } from './data';
import { queryLowPowerDeviceList } from './service';
import { queryLockerDetail } from '../../Locker/List/service';
import { queryZoneList } from '@/pages/Zones/service';
import RemoteSelect from '@/components/RemoteSelect';

const TableList: React.FC = () => {
  const [ sorter, setSorter ] = useState<string>('');
  const [ currentDevice, setCurrentDevice ] = useState<TableListItem>();
  const [ detailVisible, setDetailVisible ] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '设备编号',
      dataIndex: 'deviceNo',
      render: (_, record) => <div>{ record.deviceNo }</div>,
    },
    {
      title: '剩余电量',
      dataIndex: 'power',
      hideInSearch: true,
      render: (_, record) => (
        <Tag color={ record.power ? record.power.color : 'red' }>
          { record.power ? record.power.label : '未知' }
        </Tag>
      ),
    },
    {
      title: '状态变更时间',
            dataIndex: 'lastedStatusChangeTime',
      hideInSearch: true,
      render: (_, record) => (
        <Tag
          color={
            record.lastedStatusChangeTime.val < 0 ? record.lastedStatusChangeTime.color : undefined
          }
        >
          { record.lastedStatusChangeTime.label }
        </Tag>
      ),
    },
    {
      title: '状态刷新时间',
            dataIndex: 'lastedRefreshTime',
      hideInSearch: true,
      render: (_, record) => (
        <Tag
          color={ record.lastedRefreshTime.color }>{ record.lastedRefreshTime.label }</Tag>
      ),
      renderFormItem: (_, { onChange }) => (
        <DatePicker.RangePicker
          showTime
          format='YYYY-MM-DD HH:mm'
          onChange={ value => onChange && onChange(value) }
        />
      ),
    },
    {
      title: '所属车场',
            dataIndex: 'zone',
      render: (_, record) =>
        <div>{ record.zone ? record.zone.name : '未知' }</div>,
      renderFormItem: (_, { onChange }) => (
        <RemoteSelect
          fieldNames={ { key: 'id', value: 'id', label: 'name' } }
          onChange={ onChange }
          request={ search => queryZoneList({ name: search }) }
        />
      ),
    },
    {
      title: '绑定车位',
            dataIndex: 'spaceName',
      hideInSearch: true,
      render: (_, record) =>
        <div>{ record.space ? record.space.spaceName || '未知' : '' }</div>,
    },
    {
      title: '操作',
            dataIndex: 'option',
      hideInSearch: true,
      render: (_, record) => {
        const onClickDetail = () => {
          setCurrentDevice(record);
          setDetailVisible(true);
        };
        return (
          <div>
            <a onClick={ onClickDetail }>详情</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle='设备列表'
        actionRef={ actionRef }
        rowKey='id'
        scroll={ { x: true } }
        onChange={ (_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${ sorterResult.field }_${ sorterResult.order }`);
          }
        } }
        params={ {
          sorter,
        } }
        toolBarRender={ (action, { selectedRows }) => [
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={ async e => {
                    if (e.key === 'unbind') {
                      // TODO
                      // await handleRemove(selectedRows);
                      action?.reload();
                    }
                  } }
                  selectedKeys={ [] }
                >
                  <Menu.Item key='unbind'>批量注销</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined/>
              </Button>
            </Dropdown>
          ),
        ] }
        tableAlertRender={ () => false }
        request={ (params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return queryLowPowerDeviceList({ page, pageSize, ...filter });
        } }
        columns={ columns }
        rowSelection={ false }
      />
      <Drawer
        visible={ !!currentDevice?.id && detailVisible }
        onClose={ () => setDetailVisible(false) }
        width='30%'
      >
        { !!currentDevice?.id && detailVisible && (
          <SensorDetail deviceNo={ currentDevice?.deviceNo }
                        request={ id => queryLockerDetail({ deviceNo: id }) }/>
        ) }
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TableList;
